package org.yty.travelagencyredis.Dao.impl;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Repository;
import org.yty.travelagencyredis.Dao.MessageDao;
import org.yty.travelagencyredis.model.DTO.HistoryMessageQueryDTO;
import org.yty.travelagencyredis.model.Entity.Message;

import java.util.List;

@Repository
@RequiredArgsConstructor
public class MessageDaoImpl implements MessageDao {
    private final StringRedisTemplate redisTemplate;
    @Override
    public List<Message> getMessages(Long senderId, Long receiverId) {
        return this.getHistoryMessages(new HistoryMessageQueryDTO(senderId,receiverId,1L));
    }

    @Override
    public List<Message> getHistoryMessages(HistoryMessageQueryDTO historyMessageQueryDTO) {
        return this.redisTemplate.opsForHash().values("message")
                .stream().map(jsonString -> JSON.parseObject((String)jsonString, Message.class))
                .filter(item -> item.getSenderId().equals(historyMessageQueryDTO.getSenderId()) && item.getReceiverId().equals(historyMessageQueryDTO.getReceiverId()))
                .sorted((o1, o2) -> o2.getCreateTime().compareTo(o1.getCreateTime()))
                .skip((historyMessageQueryDTO.getPageNo() - 1) * 10).limit(10).toList();
    }

    @Override
    public void insert(Message message) {
        message.setId(IdUtil.getSnowflakeNextId());
        this.redisTemplate.opsForHash().put(Message.key, message.getId(), JSON.toJSONString(message));
    }
}
